package com.xiaobai.stream_practice;

import com.xiaobai.stream_practice.entity.Author;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.stream.Stream;

/**
 * @author wangtw
 * @ClassName CreateStream
 * @description: 创建流
 * @date 2024/2/1316:52
 */
@Slf4j
public class CreateStream {

    @Test
    public void supportCollection() {
        List<Author> authorData = PrepareWork.getAuthorData();
        // 串行流
        Stream<Author> stream = authorData.stream();
        // 并行流
        Stream<Author> parallelStream = authorData.parallelStream();

        // 双列集合，先转成单列集合再转成Stream
        Map<String, Integer> map = new HashMap<>();
        map.put("张一", 1);
        map.put("王二", 2);
        map.put("李三", 3);
        map.put("赵四", 4);
        Stream<Map.Entry<String, Integer>> entryStream = map.entrySet().stream();
    }

    @Test
    public void supportArray() {
        String[] arr = {"张一", "王二", "李三", "赵四"};
        Stream<String> stream = Arrays.stream(arr);
        stream.forEach(e -> log.info(e));
    }

    @Test
    public void supportStatic() {
        Stream<String> stream = Stream.of("张一", "王二", "李三", "赵四");
        stream.forEach(System.out::println);

        // 使用iterate创建无限流，从2开始自增2
        Stream<Integer> iterate = Stream.iterate(2, a -> a + 2);
        Optional<Integer> first = iterate.findFirst();
        System.out.println(first.get());

        // 使用generate创建无限流，
        Stream<Double> generate = Stream.generate(() -> Math.random());
        generate.forEach(integer -> System.out.println(integer));
    }
}
